//
//  WmcTeamCloudHomeCell.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/13.
//

import UIKit

class WmcTeamCloudHomeCell: WmcBaseTableCell {
    let cell_width = (Wmc_screenWidth - 82 - 12) / 3.0
    let cell_lineSpace = 6
    /// 点击了图片
    var clickImage: ((WmcMediaTeamResourceModel.WmcMediaResourceModel, UIImage?) -> Void)?
    /// 点击头像
    var clickAvater: (() -> Void)?
    /// 点击地址
    var clickLocation: (() -> Void)?

    private var model: WmcMediaTeamResourceModel?

    // Private

    private var dataSource: [WmcMediaTeamResourceModel.WmcMediaResourceModel] = []

    override func makeUI() {
        contentView.addSubview(avatarView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(collectionView)
        contentView.addSubview(locationView)

        avatarView.snp.makeConstraints { make in
            make.top.left.equalTo(17)
            make.width.height.equalTo(40)
        }

        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(avatarView.snp.top)
            make.left.equalTo(avatarView.snp.right).offset(9)
            make.height.equalTo(22)
        }

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(nameLabel.snp.bottom).offset(5)
            make.left.equalTo(nameLabel.snp.left)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(120)
        }

        locationView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(9)
            make.left.equalTo(collectionView.snp.left)
            make.right.equalTo(-16)
            make.bottom.equalTo(-20)
        }

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        avatarView.addGestureRecognizer(tap)

        locationView.button.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.gotoMap()
        }.disposed(by: rx.disposeBag)
    }

    @objc func tapAction() {
        guard let clickAvater = clickAvater else {
            return
        }
        clickAvater()
    }

    func configure(model: WmcMediaTeamResourceModel) {
        self.model = model
        /// 获取数据之后更新UI
        collectionView.snp.remakeConstraints { make in
            make.top.equalTo(nameLabel.snp.bottom).offset(5)
            make.left.equalTo(nameLabel.snp.left)
            make.right.equalTo(-16)
            make.height.equalTo(self.getHeightOfCollectionView(count: model.resources.count))
        }

        locationView.snp.remakeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(9)
            make.left.equalTo(collectionView.snp.left)
            make.right.equalTo(-16)
            make.bottom.equalTo(-20)
        }

        let memb = WmcTeamMember(name: model.getMember().showName, img: model.avatar)
        avatarView.member = memb
        nameLabel.text = model.getMember().showName

        dataSource = model.resources
        collectionView.reloadData()

        locationView.configure(model: model)
    }

    /// 计算collectionview 高度
    /// - Parameter count: 照片个数
    /// - Returns: description
    func getHeightOfCollectionView(count: Int) -> CGFloat {
        var row = count / 3
        let m = count % 3
        if m > 0 {
            row = row + 1
        }
        return CGFloat(row) * cell_width + CGFloat((row - 1) * cell_lineSpace)
    }

    lazy var avatarView: WmcMemberAvatarView = {
        let view = WmcMemberAvatarView()
        return view
    }()

    lazy var nameLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.wmc_grayH2_323233
        view.font = 14.yp.uiFont(weight: .semibold)
        view.text = "张三三"
        return view
    }()

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: cell_width, height: cell_width)
        layout.minimumLineSpacing = 6
        layout.minimumInteritemSpacing = 6
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.sectionHeadersPinToVisibleBounds = false

        let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.backgroundColor = UIColor.wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = false
        collectView.register(WmcTeamCloudPhotoCell.self, forCellWithReuseIdentifier: "WmcTeamCloudPhotoCell")
        collectView.isScrollEnabled = false
        return collectView
    }()

    lazy var locationView: WmcTeamLocationView = {
        let view = WmcTeamLocationView()
        view.isUserInteractionEnabled = true
        return view
    }()
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

extension WmcTeamCloudHomeCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in _: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcTeamCloudPhotoCell", for: indexPath) as! WmcTeamCloudPhotoCell
        if let model = dataSource.yp.object(at: indexPath.row) {
            let tModel = model.getTransformedModel()
            let date = self.model?.date ?? ""
            if date.count > 5 {
                let temp = String(date[date.index(date.startIndex, offsetBy: date.count - 5)...])
                tModel.takeTimeStr = temp
            }
            cell.bindModel(model.getTransformedModel())
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) as? WmcTeamCloudPhotoCell else { return }
        if let model = dataSource.yp.object(at: indexPath.row) {
            clickImage?(model, cell.imageView.image)
        }
    }
}

extension WmcTeamCloudHomeCell {
    func gotoMap() {
        guard let block = clickLocation else { return }
        block()

//        guard let model = self.model, !model.area.isEmpty else {
//            return WmcHudManager.toast("未获取到地点信息")
//        }
//
//        let maps = WmcMapManager.canOpenMaps()
//
//        if maps.isEmpty {
//            let alert = WmcAlertView()
//            alert.title = "温馨提示"
//            alert.msg = "请先安装地图app"
//            alert.style = .confirm(title: "确定")
//            alert.show()
//            return
//        }
//
//        let selectMapAlertView = WmcSelectMapAlertView()
//        selectMapAlertView.maps = maps
//        //addSubview(selectMapAlertView)
//
//        selectMapAlertView.clickClosure = { map in
//            if let lat = model.resources.first?.lat,let lon = model.resources.first?.lon {
//                WmcMapManager.openMap(latitude: lat, longitute: lon, name: model.area, mapType: map)
//                YPApp.CurrentVC?.dismiss(animated: true)
//            }
//        }
//
//        let presentVC = WmcPresentVC(config: .init(
//            style: .sheet(),
//            contentView: selectMapAlertView,
//            contentLayoutBlock: { make in
//                let count = maps.count <= 2 ? 3 : maps.count
//                let height = 44.wmc_autoVer + CGFloat(52 * count) + Wmc_safeAreaBottom
//                    make.left.right.bottom.equalToSuperview()
//                    make.height.equalTo(height)
//            }))
//        presentVC.show()
    }
}
